<template>
  <div class="user">
    <basic-container>
      <el-row :span="24">
        <el-col :xs="24" :sm="24" :md="4"
          class="tree">
          <h2 class="title">所有客户<span style="cursor: pointer" @click="go_add">新增客户</span></h2>
          <avue-tree
          :option="treeOption"
          :data="treeData"
          :table-loading="listLoading"
          @node-click="nodeClick"/>
        </el-col>
        <el-col :xs="24" :sm="24" :md="20" class="user__main">
          <avue-crud ref="crud" :option="option" :page.sync="page" :table-loading="listLoading" :data="list" @on-load="getList" @row-update="edit"
                     @select="selectOne"
                     @select-all="selectAll"
                     @search-change="searchChange"
                     @refresh-change="refreshChange">
            <template slot="menuLeft">
              <el-button type="primary" icon="el-icon-add" size="small" @click="createMerchantBatch" :loading="btnLoading">批量创建客户商家</el-button>
            </template>
            <template slot="menu" slot-scope="scope">
              <el-button type="text" size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row,scope.index)">编辑
              </el-button>
              <el-button type="text" size="mini" icon="el-icon-edit" @click="handleAdd(scope.row)">添加子客户
              </el-button>
            </template>
          </avue-crud>
          <el-dialog title="编辑客户组织结构" :visible.sync="visible" width="35%">
            <el-form ref="form" :model="form" label-width="80px" :label-position="'right'">
              <el-form-item label="客户">
                <span>{{form.customerName}}</span>
              </el-form-item>
              <el-form-item label="父级客户">
                <!-- <avue-input v-model="form.parentId" :dic="customerList" type="tree"/> -->
                <el-cascader
                  class="fill-width"
                  v-model="form.parentId"
                  :change-on-select="true"
                  :options="customerList"
                  :filterable="true"
                />
              </el-form-item>
              <el-form-item label="排序值">
                <el-input v-model="form.sort"></el-input>
              </el-form-item>

              <el-form-item>
                <el-button @click="close">取 消</el-button>
                <el-button type="primary" @click="save_form">确 定</el-button>
              </el-form-item>
            </el-form>
          </el-dialog>
        </el-col>
      </el-row>
    </basic-container>
  </div>

</template>

<script>
  import { fetchList, editLevel, areaTree, createMerchantBatch} from '../../api/crm/customerlevel';
  import { tableOption } from '@/const/crud/crm/customerCom';
  import { formatCascader } from '@/const/common/tool';
  import { mapGetters } from 'vuex';

  export default {
    name: 'SysUser',
    data() {
      return {
        searchForm: {},
        treeData: [],
        customerList: [],
        option: tableOption,
        treeOption: {
          nodeKey: 'id',
          addBtn: false,
          defaultExpandAll: true,
          menu: false,
          props: {
            label: 'customerName',
            value: 'id'
          }
        },
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 10, // 每页显示多少条,
          isAsc: false// 是否倒序
        },
        list: [],
        input:'',
        listLoading:false,
        visible:false,
        form:{},
        selectRowList:[],
        btnLoading: false
      }
    },
    computed: {
      ...mapGetters(['permissions'])
    },
    watch: {

    },
    created() {
        this.getHeight();
        this.option.selectable = this.selectRow
    },
    methods: {
        getHeight() {
            const tableHeight = Math.max(window.innerHeight - 430, 300)
            this.option.maxHeight = tableHeight + 'px'
        },
      nodeClick(data){
        this.getList(this.page, {parentId: data.id});
      },
      getList(page, params) {
        this.listLoading = true
        fetchList(Object.assign({
          current: page.currentPage,
          size: page.pageSize
        }, params, this.searchForm)).then(response => {
          this.list = response.data.data.records
          this.page.total = response.data.data.total
          this.listLoading = false
        })
        areaTree().then(res=>{
          this.treeData = res.data.data;
          this.customerList = formatCascader(res.data.data, 'customerName', 'id');
        })
      },
        selectRow(row, index){
            return row.merchantId === null;
        },
        selectOne(selection, row) {
            this.selectRowList = selection
        },
        selectAll(selection) {
            this.selectRowList = selection;
        },
        createMerchantBatch(){
            this.btnLoading = true;
            const selectArray = this.selectRowList;
            if (selectArray.length === 0) {
                this.$message.warning('请选择创建商家的客户');
                this.btnLoading = false;
                return;
            }
            let params = {
                customerSnList: selectArray.map(item=>item.customerSn)
            };
            createMerchantBatch(params).then(response => {
                if (response.data.code === 0) {
                    this.$message.success('批量创建客户商家成功');
                    this.getList(this.page);
                }
            }).catch(()=>{
                this.btnLoading = false;
            })
        },
      /**
       * 搜索回调
       */
      searchChange(form, done) {
                this.getList(this.page, form);
                done();
            },
      /**
       * 刷新回调
       */
      refreshChange(info) {
        this.getList(this.page, this.filterForm(info.searchForm));
      },
      go_add(){
        this.$router.push({
          path: '/customer/addCustomer'
        })
      },
      handleAdd(row){
        let query = {parentLevelId:row.id}
        this.$router.push({
          path: '/customer/addCustomer', query:query
        })
      },
      save_form(){
        let params ={
          id: this.form.id,
          customerSn: this.form.customerSn,
          parentId: Array.isArray(this.form.parentId) && this.form.parentId.length > 0 ? this.form.parentId[this.form.parentId.length -1] : '',
          sort: this.form.sort,
        }
        editLevel(params).then(response => {
          if(this.areaType == 0){
            this.$message.success('编辑成功')
          }else{
            this.$message.success('新增成功')
          }
          this.visible = false;
          this.getList(this.page);
        })
      },
      close(){
        this.getList(this.page);
        this.visible = false;
      },
      handleUpdate: function (row) {
        this.visible = true;
        this.form = row;
        // 对parentId为0的数据处理
        this.form.parentId = this.form.parentId != 0 ? this.form.parentId : null;
      },
      edit(form,index,done,loading){
        setTimeout(()=>{
          loading();
        },1000)
        setTimeout(()=>{
          let tmp = JSON.parse(JSON.stringify(form))
          let params = {
            customerSn:tmp.customerSn,
            parentId:tmp.parentId,
            sort:tmp.sort,
            id:tmp.id
          };
          editLevel(params).then(res=>{
            if(res.data.code === 0){
              this.getList(this.page);
            }
          })
          this.$message.success('编辑成功');
          done();
        },2000)
      }
    }
  }
</script>
<style lang="scss">
  .user {
    height: 100%;

    &__tree {
      padding-top: 3px;
      padding-right: 20px;
    }

    &__main {
      .el-card__body {
        padding-top: 0;
      }
    }
  }
  .list{
    line-height: 40px;
    text-align: left;
  }
  .title{
    margin-bottom: 15px;
  }
  .title span{
    font-size: 14px;
    color: #3a8ee6;
    margin-left: 20px;
  }
  .tree {
    max-height: 550px;
    overflow-x: scroll;
  }
</style>

